package ckw.gui;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.*;

import core.messages.TestMsg;

import ckw.network.ConnectionC;
import ckw.network.Komisja;
import ckw.network.StanC;
import ckw.test.TestThread;

public class TestWindow {
	Group dane;
	Shell shell; 
	ConnectionC cm;
	
	public TestWindow(Shell parent, ConnectionC _cm, StanC stanC){
		
		shell = new Shell(parent);
		dane = new Group(shell, SWT.BORDER);
		cm = _cm;
		
		Label label = new Label(dane, SWT.CENTER);
		label.setText("Testuje, prosze czekac...");
		label.pack();
		dane.pack();
		shell.pack();
		MainWindowC.center(shell);
		shell.open();
		
		ExecutorService  service = Executors.newFixedThreadPool(1);        
	    Future<ArrayList<TestMsg>>  task = service.submit(new TestThread(cm));
	    ArrayList<TestMsg> wyniki = null;
		try {
			wyniki = task.get();
			showResults(wyniki);
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
			
		}	
		
		if(service != null)
			service.shutdownNow();
		dane.pack();
		shell.pack();
		MainWindowC.center(shell);
	}

	private void showResults(ArrayList<TestMsg> wyniki) {
		dane.dispose();
		dane = new Group(shell, SWT.NONE);
		if(wyniki!=null){
			Label label2 = new Label(dane, SWT.CENTER);
			label2.setText("Wyniki testu:");
			label2.setLocation(5, 5);
			label2.pack();
			Table komisje = new Table(dane, SWT.SINGLE);
			komisje.setSize(300,200);
			komisje.setLocation(5,25);
			
			for(TestMsg tmsg: wyniki){
				TableItem ti = new TableItem(komisje, SWT.NONE);
				ti.setText(tmsg.getOkw()+ " - polaczono, aktywne terminale: " + tmsg.getIleAktywnych() + "/" + tmsg.getIleTerminali());
			}
			
			ArrayList<Komisja> niepolaczone = cm.getKomisjeOprocz(wyniki);
			for(Komisja k: niepolaczone){
				TableItem ti = new TableItem(komisje, SWT.NONE);
				ti.setText(k.getId() + " - niepolaczono");
			}
					
		} else {
			Label label2 = new Label(dane, SWT.CENTER);
			label2.setText("Blad");
			label2.pack();
		}
		
	}
}
